<?php
function M($module)
{
	static $modules = array();
	if(empty($modules[$module]))
	{
		require_once import("module/".strtolower($module));
		$m = ucfirst($module)."Module";
		$modules[$module] = new $m();
		unset($m);
	}
	return $modules[$module];
}

function S($service)
{
	static $services = array();
	if(empty($services[$service]))
	{
		require_once import("service/".strtolower($service));
		$s = ucfirst($service)."Service";
		$services[$service] = new $s();
		unset($s);
	}

	return $services[$service];
}

function U($type,$args)
{
	global $_FANWE;
	static $is_rewrite = NULL,$is_vdns = NULL,$site_url = NULL;

    if ($is_rewrite === NULL)
    {
        $is_rewrite = intval($_FANWE['setting']['url_route']);
    }

	if ($site_url === NULL)
    {
        $site_url = $_FANWE['site_url'];
    }

	$depr = '-';
	
	$url = SITE_PATH.'/';

	$is_suffix = true;

	$apps = explode('/',$type);
	$module = $apps[0];
	$action = isset($apps[1]) ? $apps[1] : 'index';

	$query = '';

	if($is_rewrite == 0)
	{
		$query = http_build_query($args);
		if(!empty($query))
			$query = '&'.$query;
	}
	else
	{
		foreach($args as $var=>$val)
		{
			$query .= $depr.$var.$depr.$val;
		}
	}

	switch($type)
	{
		case 'city':
			if($is_rewrite == 0)
				$url .= 'index.php?action=index'.$query;
			else
			{
				$is_suffix = false;

				if($is_vdns == 0)
					$url .= $args['city_py'];
				else
					$url = str_replace('www',$args['city_py'],$site_url);
			}
		break;
		
		case 'index/index':
			$is_suffix = false;
			$url = '/';
		break;

		case 'now/index':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				if(empty($query))
					$is_suffix = false;
				else
					$url .= 'now'.$query;
			}
		break;

		case 'now/today':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				if(empty($query))
					$is_suffix = false;

				$url .= 'today'.$query;
			}
		break;

		case 'now/custom':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				if(empty($query))
					$is_suffix = false;

				$url .= 'custom'.$query;
			}
		break;

		case 'now/search':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				if(empty($query))
					$is_suffix = false;

				$url .= 'search'.$query;
			}
		break;

		case 'site/index':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				$is_suffix = false;
				$url .= 'site';
			}
		break;

		case 'site/show':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
				$url .= 'site/'.intval($args['id']);
		break;

		case 'site/go':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
				$url .= 'site/go-'.intval($args['id']);
		break;

		case 'goods/index':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				if(empty($query))
					$is_suffix = false;

				$url .= 'group'.$query;
			}
		break;

		case 'goods/search':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				if(empty($query))
					$is_suffix = false;

				$url .= 'expired'.$query;
			}
		break;

		case 'goods/show':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				$url .= 'group/'.intval($args['id']);
				if(isset($args['spread']))
					$url .= $depr.intval($args['spread']);
			}
		break;

		case 'goods/go':
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
			{
				$url .= 'group/go-'.intval($args['id']);
				if(isset($args['spread']))
					$url .= $depr.intval($args['spread']);
			}
		break;

		default:
			if($is_rewrite == 0)
				$url .= $module.'.php?action='.$action.$query;
			else
				$url .= $module.$depr.$action.$query;
		break;
	}

	if($is_rewrite > 0 && $is_suffix)
		$url .= '.html';

	return $url;
}

function getRewriteArgs($keys)
{
	global $_FANWE;
	$args = trim($_FANWE['request']['args']);

	foreach($keys as $key)
	{
		preg_match("/$key-(.+?)(?:$|-)/is",$args,$value);
		if(count($value) > 1)
		{
			$_FANWE['request'][$key] = $value[1];
			if($key == 'page')
				$_FANWE['page'] = $value[1];
		}
	}
	unset($_FANWE['request']['args']);
}

function buildPage($type,$args,$total_count,$page = 1,$page_size = 0,$url='',$offset = 5)
{
	global $_FANWE;

	$pager['total_count'] = intval($total_count);
	$pager['page'] = $page;
	$pager['page_size'] = ($page_size == 0) ? ($_FANWE['setting']['page_listrows'] > 0 ? $_FANWE['setting']['page_listrows'] : 20) : $page_size;
	/* page 总数 */
	$pager['page_count'] = ($pager['total_count'] > 0) ? ceil($pager['total_count'] / $pager['page_size']) : 1;

	/* 边界处理 */
	if ($pager['page'] > $pager['page_count'])
		$pager['page'] = $pager['page_count'];

	$pager['limit'] = ($pager['page'] - 1) * $pager['page_size'] . "," . $pager['page_size'];

	$page_prev  = ($pager['page'] > 1) ? $pager['page'] - 1 : 1;
	$page_next  = ($pager['page'] < $pager['page_count']) ? $pager['page'] + 1 : $pager['page_count'];

	if (!empty($url))
	{
		$pager['page_first'] = $url . 1;
		$pager['page_prev']  = $url . $page_prev;
		$pager['page_next']  = $url . $page_next;
		$pager['page_last']  = $url . $pager['page_count'];
	}
	else
	{
		$args['page'] = '_page_';
		$page_url = U($type,$args);

		$pager['page_first'] = str_replace('_page_',1,$page_url);
		$pager['page_prev']  = str_replace('_page_',$page_prev,$page_url);
		$pager['page_next']  = str_replace('_page_',$page_next,$page_url);
		$pager['page_last']  = str_replace('_page_',$pager['page_count'],$page_url);
	}

	$pager['page_nums'] = array();

	if($pager['page_count'] <= $offset * 2)
	{
		for ($i=1; $i <= $pager['page_count']; $i++)
		{
			$pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
		}
	}
	else
	{
		if($pager['page'] - $offset < 2)
		{
			$temp = $offset * 2;

			for ($i=1; $i<=$temp; $i++)
			{
				$pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
			}

			$pager['page_nums'][] = array('name'=>'...');
			$pager['page_nums'][] = array('name' => $pager['page_count'],'url' => empty($url) ? str_replace('_page_',$pager['page_count'],$page_url) : $url . $pager['page_count']);
		}
		else
		{
			$pager['page_nums'][] = array('name' => 1,'url' => empty($url) ? str_replace('_page_',1,$page_url) : $url . 1);
			$pager['page_nums'][] = array('name'=>'...');
			$start = $pager['page'] - $offset + 1;
			$end = $pager['page'] + $offset - 1;

			if($pager['page_count'] - $end > 1)
			{
				for ($i=$start;$i<=$end;$i++)
				{
					$pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
				}

				$pager['page_nums'][] = array('name'=>'...');
				$pager['page_nums'][] = array('name' => $pager['page_count'],'url' => empty($url) ? str_replace('_page_',$pager['page_count'],$page_url) : $url . $pager['page_count']);
			}
			else
			{
				$start = $pager['page_count'] - $offset * 2 + 1;
				$end = $pager['page_count'];
				for ($i=$start;$i<=$end;$i++)
				{
					$pager['page_nums'][] = array('name' => $i,'url' => empty($url) ? str_replace('_page_',$i,$page_url) : $url . $i);
				}
			}
		}
	}

	return $pager;
}

function import($file_name, $folder = '')
{
	global $_FANWE;
	static $sufix = array(
		'module'=>'.module',
		'service'=>'.service',
		'class'=>'.class',
		'function' => '.func',
		'include' => '.inc',
		'language' => '.lang',
		'cache' => '.cache',
	);

	$file_path = FANWE_ROOT.'core';
	if(strstr($file_name, '/'))
	{
		list($pre, $name) = explode('/', $file_name);

		$insert = '';
		if($pre == 'language')
			$insert = $_FANWE['setting']['lang_name'].'/';

		return "{$file_path}/{$pre}/".$insert.(empty($folder) ? "" : $folder . "/")."{$name}".$sufix[$pre].".php";
	}
	else
	{
		return "{$file_path}/".(empty($folder) ? "" : $folder . "/")."{$file_name}.php";
	}
}

//设置时区
function timezoneSet($timezone)
{
	if(function_exists('date_default_timezone_set'))
		@date_default_timezone_set('Etc/GMT'.($timezone > 0 ? '-' : '+').(abs($timezone)));
}

/**
 * 用于检测当前用户IP的可操作性,time_span为验证的时间间隔 秒
 *
 * @param string $ip_str  IP地址
 * @param string $module  操作的模块     *
 * @param integer $time_span 间隔
 * @param integer $id   操作的数据
 *
 * @return boolean
 */
function checkIpOperation($module,$time_span = 0,$id = 0)
{
	global $_FANWE;

	$key = $_FANWE['uid'].'_check_'.$module.($id > 0 ? '_'.$id : '');

	if(empty($_FANWE['cookie'][$key]))
		return false;
	else
	{
		list($cip,$time) = fAddslashes(explode("\t", authcode($_FANWE['cookie'][$key], 'DECODE')));

		if(TIMESTAMP - $time < $time_span)
		{
			return false;
		}
		else
		{
			fSetCookie($key, authcode($_FANWE['client_ip']."\t".TIMESTAMP, 'ENCODE'),604800, 1, true);
			return true;
		}
	}
}

function cutStr($string, $length, $dot = '...')
{
	if(strlen($string) <= $length)
		return $string;

	$pre = '{%';
	$end = '%}';
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while($n < strlen($string))
		{
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
			{
				$tn = 1; $n++; $noc++;
			}
			elseif(194 <= $t && $t <= 223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}
			elseif(224 <= $t && $t <= 239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}
			elseif(240 <= $t && $t <= 247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}
			elseif(248 <= $t && $t <= 251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}
			elseif($t == 252 || $t == 253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}
			else
			{
				$n++;
			}

			if($noc >= $length)
				break;
		}

		if($noc > $length)
			$n -= $tn;

		$strcut = substr($string,0,$n);

	}
	else
	{
		for($i = 0; $i < $length; $i++)
		{
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut.$dot;
}

function getStrLen($str)
{
    $length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

    if ($length)
    {
        return strlen($str) - $length + intval($length / 3) * 2;
    }
    else
    {
        return strlen($str);
    }
}

//获取字节数
function getBytes($val)
{
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last)
	{
        case 'g': $val *= 1024;
        case 'm': $val *= 1024;
        case 'k': $val *= 1024;
    }

    return $val;
}

//错误处理
function systemError($message, $show = true, $save = true, $halt = true)
{
	require_once import('class/error');
	FanweError::systemError($message, $show, $save, $halt);
}

//显示成功信息
function showSuccess($title, $message,$jump_url,$wait = 3)
{
	global $_FANWE;
	$cache_args = array(
		$_FANWE['cookie']['city_py'],
	);

	$cache_file = getTplCache('page/success',$cache_args);

	if(!@include($cache_file))
		include template('page/success');

	display($cache_file);
	exit;
}

//2011-01-30 update
//显示错误信息
function showError($title, $message,$jump_url,$wait = 3,$is_close = false)
{
	global $_FANWE;
	$cache_args = array(
		$_FANWE['cookie']['city_py'],
	);

	if($is_close)
		$cache_file = getTplCache('page/close',$cache_args);
	else
		$cache_file = getTplCache('page/error',$cache_args);

	if(!@include($cache_file))
	{
		if($is_close)
			include template('page/close');
		else
			include template('page/error');
	}

	display($cache_file);
	exit;
}

//查询字符串是否存在
function strExists($string, $find)
{
	return !(strpos($string, $find) === FALSE);
}

//获取是否为搜索引擎爬虫
function checkRobot($userAgent = '')
{
	static $kwSpiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
	static $kwBrowsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';

	$userAgent = empty($userAgent) ? $_SERVER['HTTP_USER_AGENT'] : $userAgent;

	if(!strExists($userAgent, 'http://') && preg_match("/($kwBrowsers)/i", $userAgent))
		return false;
	elseif(preg_match("/($kwSpiders)/i", $userAgent))
		return true;
	else
		return false;
}

//获取网站域名
function getSiteHost()
{
	return 'http://'.preg_replace("/\:\d+/", '', $_SERVER['HTTP_HOST']).($_SERVER['SERVER_PORT'] && $_SERVER['SERVER_PORT'] != 80 ? ':'.$_SERVER['SERVER_PORT'] : '');
}

//2011-02-28
//获取网站相对路径
function getSitePath()
{
    @include FANWE_ROOT.'./public/config.global.php';
	return SITE_PATH;
}

//获取当前url
function getUrl()
{
	if (isset($_SERVER['REQUEST_URI']))
		$uri = $_SERVER['REQUEST_URI'];
	else
	{
		if (isset($_SERVER['argv']))
			$uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
		else
			$uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
	}
	return $uri;
}

function getUrlHost($url)
{
	$urls = parse_url($url);
	return $urls['host'];
}

//2011-01-30 update
function getScriptDomain()
{
	$nav_host = getUrlHost(SITE_URL);
	$bbs_host = getUrlHost(BBS_URL);
	$domain = false;

	if($nav_host != $bbs_host)
	{
		$domain = explode(".", $nav_host);
		$domain_count = count($domain);
		if($domain_count > 2)
			$domain = $domain[$domain_count-2].".".$domain[$domain_count-1];
		else
			$domain = $nav_host;
	}

	return $domain;
}


function parseUrl($url)
{
	$parse_url = parse_url($url);
	return (!empty($parse_url['scheme']) && !empty($parse_url['host']));
}

//获取客户端IP
function getClientIp()
{
	$ip = $_SERVER['REMOTE_ADDR'];
	if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP']))
	{
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	}
	elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches))
	{
		foreach ($matches[0] AS $xip)
		{
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip))
			{
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}

//字符转义
function fAddslashes($string)
{
	if(is_array($string))
	{
		foreach($string as $key => $val)
		{
			unset($string[$key]);
			$string[addslashes($key)] = fAddslashes($val);
		}
	}
	else
	{
		$string = addslashes($string);
	}

	return $string;
}

function setGlobal($key , $value, $group = NULL)
{
	global $_FANWE;
	$k = explode('/', $group === NULL ? $key : $group.'/'.$key);
	switch (count($k))
	{
		case 1: $_FANWE[$k[0]] = $value; break;
		case 2: $_FANWE[$k[0]][$k[1]] = $value; break;
		case 3: $_FANWE[$k[0]][$k[1]][$k[2]] = $value; break;
		case 4: $_FANWE[$k[0]][$k[1]][$k[2]][$k[3]] = $value; break;
		case 5: $_FANWE[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] =$value; break;
	}
	return true;
}

function getGlobal($key, $group = NULL)
{
	global $_FANWE;
	$k = explode('/', $group === NULL ? $key : $group.'/'.$key);
	switch (count($k))
	{
		case 1: return isset($_FANWE[$k[0]]) ? $_FANWE[$k[0]] : NULL; break;
		case 2: return isset($_FANWE[$k[0]][$k[1]]) ? $_FANWE[$k[0]][$k[1]] : NULL; break;
		case 3: return isset($_FANWE[$k[0]][$k[1]][$k[2]]) ? $_FANWE[$k[0]][$k[1]][$k[2]] : NULL; break;
		case 4: return isset($_FANWE[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_FANWE[$k[0]][$k[1]][$k[2]][$k[3]] : NULL; break;
		case 5: return isset($_FANWE[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_FANWE[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : NULL; break;
	}
	return NULL;
}

function random($length, $numeric = 0)
{
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++)
	{
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

/**  
 * 生成表单随机数
 * @param string $specialadd 增加文本
 * @return string
 */
function formHash($specialadd = '')
{
	global $_FANWE;
	return substr(md5(substr(TIME_UTC, 0, -7).$_FANWE['user_name'].$_FANWE['uid'].$_FANWE['authkey'].$specialadd), 8, 8);
}

function fSetCookie($var, $value = '', $life = 0, $prefix = 1, $http_only = false,$is_write = true)
{
	global $_FANWE;
	$config = $_FANWE['config']['cookie'];
	$var = ($prefix ? $config['cookie_pre'] : '').$var;
	if($is_write)
	{
		$_FANWE['cookie'][$var] = $value;
		$_COOKIE[$var] = $var;
	}

	if($value == '' || $life < 0)
	{
		$value = '';
		$life = -1;
	}

	$life = $life > 0 ? TIMESTAMP + $life : ($life < 0 ? TIMESTAMP - 31536000 : 0);
	$path = $http_only && PHP_VERSION < '5.2.0' ? $config['cookie_path'].'; HttpOnly' : $config['cookie_path'];

	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0')
	{
		setcookie($var, $value, $life, $path, $config['cookie_domain'], $secure);
	}
	else
	{
		setcookie($var, $value, $life, $path, $config['cookie_domain'], $secure, $http_only);
	}
}

function getCookie($key)
{
	global $_FANWE;
	return isset($_FANWE['cookie'][$key]) ? $_FANWE['cookie'][$key] : '';
}

/**  
 * 更新session
 * @param bool $force 强制更新
 * @return bool
 */
function updateSession($force = false) {

	global $_FANWE;
	static $updated = false;

	if(!$updated)
	{
		$fanwe = & FanweService::instance();
		foreach($fanwe->session->var as $k => $v)
		{
			if(isset($_FANWE['user'][$k]) && $k != 'last_activity')
				$fanwe->session->set($k, $_FANWE['user'][$k]);
		}

		$fanwe->session->update();

		$updated = true;
	}
	
	return $updated;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
	global $_FANWE;
	$ckey_length = 4;
	$key = md5($key != '' ? $key : $_FANWE['authkey']);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++)
	{
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++)
	{
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++)
	{
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE')
	{
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
		{
			return substr($result, 26);
		} else {
			return '';
		}
	}
	else
	{
		return $keyc.str_replace('=', '', base64_encode($result));
	}

}

function lang($file, $var = NULL, $default = NULL)
{
	global $_FANWE;

	$key = $file."_lang";

	if(!isset($_FANWE['lang'][$key]))
	{
		include import("language/$file");
		$_FANWE['lang'][$key] = $lang;
	}

	$return = $var !== NULL ? (isset($_FANWE['lang'][$key][$var]) ? $_FANWE['lang'][$key][$var] : NULL) : $_FANWE['lang'][$key];

	$return = $return === NULL ? ($default !== NULL ? $default : $var) : $return;

	return $return;
}

function getTplCache($file, $args, $tpl_dir = '')
{
	global $_FANWE;
	$tpl_dir = $tpl_dir ? $tpl_dir : './tpl/'.$_FANWE['setting']['tpl_dir'];
	$tpl_file = $tpl_dir.'/'.$file.'.htm';

	return FANWE_ROOT.'./public/tpl/caches/'.str_replace('/', '_', $file).'/'.md5($tpl_file.implode(',',$args)).".htm";
}

function checkTplRefresh($main_tpl, $sub_tpl, $time_compare, $cache_file, $tpl_dir, $file)
{
	global $_FANWE;
	static $tpl_refresh = NULL;
	if($tpl_refresh === NULL)
	{
		$tpl_refresh = $_FANWE['config']['output']['tpl_refresh'];
	}

	if(empty($time_compare) || $tpl_refresh == 1 || ($tpl_refresh > 1 && !(TIMESTAMP % $tpl_refresh)))
	{
		if(empty($time_compare) || @filemtime(FANWE_ROOT.$sub_tpl) > $time_compare)
		{
			require_once import('class/template');
			$template = new Template();
			$template->parseTemplate($main_tpl, $tpl_dir, $file, $cache_file);
			return TRUE;
		}
	}
	return FALSE;
}

function template($file, $tpl_dir = '', $get_tpl_file = 0)
{
	global $_FANWE;

	$tpl_dir = $tpl_dir ? $tpl_dir : './tpl/'.$_FANWE['setting']['tpl_dir'];
	$tpl_file = $tpl_dir.'/'.$file.'.htm';
	$cache_file = './public/tpl/compiled/'.str_replace('/', '_', $file).'.tpl.php';

	if($get_tpl_file)
		return $tpl_file;

	checkTplRefresh($tpl_file, $tpl_file, @filemtime(FANWE_ROOT.$cache_file), $cache_file, $tpl_dir, $file);
	return FANWE_ROOT.$cache_file;
}

function tplFetch($file,&$args = array(), $tpl_dir = '')
{
	global $_FANWE;

	if(!empty($args))
	{
		foreach($args as $key=>$val)
		{
			$$key = &$args[$key];
		}
	}

	ob_start();
	include template($file,$tpl_dir);
	$content = ob_get_contents();
	ob_end_clean();

	return $content;
}

function tplString($string,$cache_key,&$args = array())
{
	global $_FANWE;

	if(!empty($args))
	{
		foreach($args as $key=>$val)
		{
			$$key = &$args[$key];
		}
	}

	if(empty($cache_key))
		$cache_key = md5($string);

	$cache_file = FANWE_ROOT.'./public/tpl/caches/'.$cache_key.'.htm';

	if(!file_exists($cache_file))
	{
		if(makeDir(preg_replace("/^(.*)\/.*?\.htm$/is", "\\1", $cache_file)))
		{
			require_once import('class/template');
			$template = new Template();
			$string = $template->parseString($string);
			writeFile($cache_file,$string);
		}
	}

	ob_start();
	include $cache_file;
	$content = ob_get_contents();
	ob_end_clean();

	return $content;
}

function display($cache_file,$is_return = false,$is_session = true)
{
	global $_FANWE;

	if(!empty($cache_file) && !@file_exists($cache_file) && diskfreespace(FANWE_ROOT.'./public/tpl/caches') > 1000000)
	{
		if(makeDir(preg_replace("/^(.*)\/.*?\.htm$/is", "\\1", $cache_file)))
		{
			if($fp = @fopen($cache_file, 'w'))
			{
				flock($fp, LOCK_EX);
				fwrite($fp, ob_get_contents());
			}
			@fclose($fp);
			chmod($cache_file, 0777);
		}
	}

	require import('function/dynamic');
	$content = ob_get_contents();
	ob_end_clean();

	$content = preg_replace('/<!--dynamic\s+(.+?)(?:|\sargs=(.*?))-->/ies', "\\1('\\2');", $content);
	
	if($is_session)
		updateSession();
	
	if($is_return)
		return $content;

	$_FANWE['gzip_compress'] ? ob_start('ob_gzhandler') : ob_start();

	echo $content;
}

function clearDir($dir)
{
	if(!file_exists($dir))
		return;

	$directory = dir($dir);

	while($entry = $directory->read())
	{
		if($entry != '.' && $entry != '..')
		{
			$filename = $dir.'/'.$entry;
			if(is_dir($filename))
				clearDir($filename);

			if(is_file($filename))
				@unlink($filename);
		}
	}

	$directory->close();
}

/**
 * 检查目标文件夹是否存在，如果不存在则自动创建该目录
 *
 * @access      public
 * @param       string      folder     目录路径。不能使用相对于网站根目录的URL
 *
 * @return      bool
 */
function makeDir($folder)
{
    $reval = false;
    if (!file_exists($folder))
    {
		$folder = str_replace(FANWE_ROOT,'',$folder);
        /* 如果目录不存在则尝试创建该目录 */
        @umask(0);
        /* 将目录路径拆分成数组 */
        preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
        /* 如果第一个字符为/则当作物理路径处理 */
        $base = FANWE_ROOT.(($atmp[0][0] == '/') ? '/' : '');

        /* 遍历包含路径信息的数组 */
        foreach ($atmp[1] AS $val)
        {
            if ('' != $val)
            {
                $base .= $val;
                if ('..' == $val || '.' == $val)
                {
                    /* 如果目录为.或者..则直接补/继续下一个循环 */
                    $base .= '/';
                    continue;
                }
            }
            else
            {
                continue;
            }
            $base .= '/';

            if (!file_exists($base))
            {
                /* 尝试创建目录，如果创建失败则继续循环 */
                if (@mkdir(rtrim($base, '/'), 0777))
                {
                    @chmod($base, 0777);
                    $reval = true;
                }
            }
        }
    }
    else
    {
        /* 路径已经存在。返回该路径是不是一个目录 */
        $reval = is_dir($folder);
    }

    clearstatcache();
    return $reval;
}

function utf8ToGB($str)
{
	static $chinese = NULL;
	if($chinese === NULL)
	{
		require_once import('class/chinese');
		$chinese = new Chinese('UTF-8','GBK');
	}
	return $chinese->convert($str);
}

function gbToUTF8($str)
{
	static $chinese = NULL;
	if($chinese === NULL)
	{
		require_once import('class/chinese');
		$chinese = new Chinese('GBK','UTF-8');
	}
	return $chinese->convert($str);
}

/**
 * 对 MYSQL LIKE 的内容进行转义
 *
 * @access      public
 * @param       string      string  内容
 * @return      string
 */
function mysqlLikeQuote($str)
{
    return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%', "\'" => "\\\\\'"));
}

function fHeader($string, $replace = true, $http_response_code = 0)
{
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if(empty($http_response_code) || PHP_VERSION < '4.3' )
	{
		@header($string, $replace);
	}
	else
	{
		@header($string, $replace, $http_response_code);
	}

	if(preg_match('/^\s*location:/is', $string))
	{
		exit();
	}
}

/**
 * 显示指定名称的广告位布局
 */
function getAdvLayout($id,$count = '',$target='')
{
	global $_FANWE;
	$layout = DB::fetchFirst('SELECT rec_id AS pid,item_limit AS acount,target_id AS target FROM '.DB::table('layout')." WHERE layout_id ='$id' AND tmpl = '".$_FANWE['setting']['tpl_dir']."' AND rec_module = 'AdvPosition'");

	if(!$layout)
		return '';

	if($count != '')
		$layout['acount'] = intval($count);

	if($target != '')
		$layout['target'] = explode(',',$target);

	return getAdvPosition($layout['pid'],$layout['acount'],$layout['target']);
}

/**
 * 显示指定ID的广告位
 */
function getAdvPosition($pid = 0,$count = 0,$target='')
{
	global $_FANWE;

	$ap = DB::fetchFirst('SELECT * FROM '.DB::table('adv_position').' WHERE id ='.$pid);
	if(!$ap)
		return '';

	$where = "a.status = 1 AND a.is_show = 1 AND a.position_id = '$pid'";
	if($target != '')
		$where .= ' AND a.target_key'.DB::createIN($target);

	if(!defined('CURRENT_CITY_PY') || CURRENT_CITY_PY == CHINA_CITY_PY)
	{
		$sql = 'SELECT a.*,
				IF((SELECT COUNT(city_id) FROM '.DB::table('auction_city').' WHERE auction_id = a.auction_id AND city_id = 0) > 0,1,0) AS all_ad
				FROM '.DB::table('adv').' AS a
				WHERE '.$where.'
				HAVING a.auction_id = 0 OR all_ad = 1
				ORDER BY all_ad DESC,a.sort DESC,a.id ASC';
	}
	else
	{
		$sql = 'SELECT a.*,
				IF((SELECT COUNT(city_id) FROM '.DB::table('auction_city').' WHERE auction_id = a.auction_id AND city_id = 0) > 0,1,0) AS all_ad,
				IF((SELECT COUNT(city_id) FROM '.DB::table('auction_city').' WHERE auction_id = a.auction_id AND city_id = '.intval($_FANWE['current_city']['id']).') > 0,1,0) AS city_ad
				FROM '.DB::table('adv').' AS a
				WHERE '.$where.' 
				HAVING a.auction_id = 0 OR all_ad = 1 OR city_ad = 1 
				ORDER BY city_ad DESC,all_ad DESC,a.sort DESC,a.id ASC';
	}

	if($count > 0)
		$sql .= ' LIMIT 0,'.$count;

	$adv_res = DB::query($sql);

	$adv_list = array();

	while($adv = DB::fetch($adv_res))
	{
		$adv['html'] = getAdvHTML($adv,$ap);
		$adv['url'] = urlencode(U("adv/show",array("id"=>$adv['id'])));
		$adv_list[] = $adv;
	}

	$ap['adv_list'] = $adv_list;
	return $ap;
}

function getAdvHTML($adv,$ap)
{
	if($adv['width'] > 0)
		$ap['width'] = $adv['width'];

	if($adv['height'] > 0)
		$ap['height'] = $adv['height'];

	if($ap['width'] == 0)
		$ap['width']="";
	else
		$ap['width']=" width='".$ap['width']."'";

	if($ap['height'] == 0)
		$ap['height']="";
	else
		$ap['height']=" height='".$ap['height']."'";

	switch($adv['type'])
	{
		case '1':
			if($adv['url']=='')
				$adv_str = "<img src='".SITE_PATH.$adv['code']."'".$ap['width'].$ap['height']."/>";
			else
				$adv_str = "<a href='".U("adv/show",array("id"=>$adv['id']))."' target='_blank'><img src='".SITE_PATH.$adv['code']."'".$ap['width'].$ap['height']."/></a>";
			break;
		case '2':
			$adv_str = "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0'".$ap['width'].$ap['height'].">".
					   "<param name='movie' value='".SITE_PATH.$adv['code']."' />".
    				   "<param name='quality' value='high' />".
					   "<param name='menu' value='false' />".
					   "<embed src='".SITE_PATH.$adv['code']."' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash'".$ap['width'].$ap['height']."></embed>".
					   "</object>";
			break;
		case '3':
			$adv_str = $adv['code'];
			break;
	}

	return $adv_str;
}

/**
 写入文件内容
 $filepat 文件路径
 $content 写入内容
 $type　　 写入方式 w:将文件指针指向文件头并将文件大小截为零 a:将文件指针指向文件末尾
*/
function writeFile($filepath,$content,$type='w')
{
	$is_success = false;

	if($fp = fopen($filepath,$type))
	{
		$start_time = microtime();
		do
		{
	        $is_write = flock($fp, LOCK_EX);
			if(!$is_write)
				usleep(round(rand(0,100) * 1000));
		}
		while(!$is_write && ((microtime() - $start_time) < 10000));

		if ($is_write && fwrite($fp, $content))
	  		$is_success = true;

		flock($fp,LOCK_UN);
		fclose($fp);
		@chmod($filepath, 0777);
	}

	return $is_success;
}

/**
 * 初始化会员数据整合类
 *
 * @access  public
 * @return  object
 */
function &init_users()
{
    static $cls = null;
    if ($cls != null)
    {
        return $cls;
    }
	
	global $_FANWE;
	
	$code = $_FANWE['setting']['integrate_code'];
    include_once(FANWE_ROOT . './ThinkPHP/Vendor/integrates/'.$code.'.php');
    $cfg = unserialize($_FANWE['setting']['integrate_config']);
	$cfg['is_thinkphp'] = false;
	
    $cls = new $code($cfg);

    return $cls;
}

/**
 * utf8字符转Unicode字符
 * @param string $char 要转换的单字符
 * @return void
 */
function utf8ToUnicode($char)
{
	switch(strlen($char))
	{
		case 1:
			return ord($char);
		case 2:
			$n = (ord($char[0]) & 0x3f) << 6;
			$n += ord($char[1]) & 0x3f;
			return $n;
		case 3:
			$n = (ord($char[0]) & 0x1f) << 12;
			$n += (ord($char[1]) & 0x3f) << 6;
			$n += ord($char[2]) & 0x3f;
			return $n;
		case 4:
			$n = (ord($char[0]) & 0x0f) << 18;
			$n += (ord($char[1]) & 0x3f) << 12;
			$n += (ord($char[2]) & 0x3f) << 6;
			$n += ord($char[3]) & 0x3f;
			return $n;
	}
}

/**
 * utf8字符串分隔为unicode字符串
 * @param string $str 要转换的字符串
 * @param string $pre
 * @return string
 */
function segmentToUnicode($str,$pre = '')
{
	$arr = array();
	$str_len = mb_strlen($str,'UTF-8');
	for($i = 0;$i < $str_len;$i++)
	{
		$s = mb_substr($str,$i,1,'UTF-8');
		if($s != ' ' && $s != '　')
		{
			$arr[] = $pre.'ux'.utf8ToUnicode($s);
		}
	}
	
	$arr = array_unique($arr);
	
	return implode(' ',$arr);
}

/**
 * 清除符号
 * @param string $str 要清除符号的字符串
 * @return string
 */
function clearSymbol($str)
{
	static $symbols = NULL;
	if($symbols === NULL)
	{
		$symbols = file_get_contents(FANWE_ROOT.'./public/table/symbol.table');
		$symbols = explode("\r\n",$symbols);
	}
	
	return str_replace($symbols,"",$str);
}

function clearRepeat($str)
{
	$arr = array();
	$str_len = mb_strlen($str,'UTF-8');
	for($i = 0;$i < $str_len;$i++)
	{
		$s = mb_substr($str,$i,1,'UTF-8');
		if($s != ' ' && $s != '　')
		{
			$arr[] = $s;
		}
	}
	
	$arr = array_unique($arr);
	
	return implode('',$arr);
}
?>